package net.peihuan.controller;


import net.peihuan.entity.Article;
import net.peihuan.entity.Category;
import net.peihuan.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @RequestMapping(value = "/selectAllCategoriesWithArticles")
    @ResponseBody
    public List<Category> selectAllCategoriesWithArticles(){
        List<Category> categories= categoryService.findAllWithArticles();
        for(Category category:categories){
            //如果某一个分类没文章，那么必须要给设置值，否则null json会出错
            if (category.getArticles().get(0).getArticleid()==null){
                category.getArticles().get(0).setArticleid(0);
                category.getArticles().get(0).setTitle("00000");
                category.getArticles().get(0).setWeight(0);
                category.getArticles().get(0).setClick(0);
                category.getArticles().get(0).setContent("000000");
                category.getArticles().get(0).setPubdate(new Date());
            }
        }
        return categories;
    }

    //查询分类的个数
    @RequestMapping("/count")
    @ResponseBody
    public int countCategory(){
        return categoryService.count();
    }

    @RequestMapping("/selectAllCategories")
    @ResponseBody
    public List<Category>  selectAllCategories(){
        return categoryService.findAll();
    }

    @RequestMapping(value = "/saveCategory")
    @ResponseBody  //使用@ResponseBody将返回值转换为JSON
    public Category saveCategory(@RequestBody Category category){
        int cnt=categoryService.save(category);
        if(cnt==1){
            return category;
        }else
            return null;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public int delete(HttpServletRequest request){
        int id =Integer.parseInt(request.getParameter("id"));
        return categoryService.delete(id);
    }

    @RequestMapping("/selectCategory")
    @ResponseBody
    public Category selectCategory(HttpServletRequest request){
        int id =Integer.parseInt(request.getParameter("id"));

        return categoryService.find(id);
    }

    @RequestMapping(value="/update")
    @ResponseBody
    public String update(@RequestBody Category category){

        if(categoryService.update(category)==1)
            return "success";
        else
            return "failed";
    }

}
